<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

class RptModel extends NewzanModel
{

    protected $tableName = 'rpt_campaign';
    protected $me = null;
    protected $adgroup_id = 0;
    protected $campaign_id = 0;
    protected $subwayToken = null;
    
    
	public function _initialize()
	{
		parent :: _initialize();
		$this->me = session('me');
	}
	
	/**
	 * 	调用API获取用户不同类型(campaign,adgroup,adgroupplace,adgroupcreative,demographic)的分类数据
	 *  为了增加初始化速度，开始的时候只需要汇总数据即可，这样的话可以先按需获取插入，后台在运行获取更细节数据
	 *
	 *  @deprecated 未写完, 也未使用
	 *  
	 *  @param unknown $entity
	 */
	public function getDetailedData( $entity , $campaign_id=0 , $adgroup_id=0 , $startTime=null , $endTime=null)
	{
		
		$subway_token = $this->getSubway();
		$req['nick'] = $this->me['nick'];
		$req['start_time'] = $startTime;
		$req['end_time'] = $endTime;
		$req['page_no'] = $pageNo;
		$req['page_size'] = $pageSize;
		$req['source'] = 'SUMMARY';
		$req['subway_token'] = $subway_token;
		$req['campaign_id'] = $CampaignId;
		$req['search_type'] = 'SUMMARY';
		$req['campaign_id'] = $campaign_id;
		$req['adgroup_id'] = $adgroup_id;
		
		switch($entity) {
			
			case 'rpt_customer':
				$resp = $this->_api->SimbaRptCustbaseGetRequest($req);
				return (array) $resp['rpt_cust_base_list'];
			break;
			//campaign
			case 'rpt_campaign':
				$resp = $this->_api->SimbaRptCampaignbaseGetRequest($req);
				return (array) $resp['rpt_campaign_base_list'];
			break;
			
			case 'rpt_adgroup':
				$resp = $this->_api->SimbaRptCampadgroupbaseGetRequest($req);
				return (array) $resp['rpt_campadgroup_base_list'];
			break;
			
			//分类数据 已经删除这个API （API不存在）
			case 'rpt_adgroup_place':
				$resp = $this->_api->SimbaRptAdgroupnonsearchbaseGetRequest($req);
				return (array) $resp['rpt_nonsearch_base_list'];
			break;
			
			case 'rpt_adgroup_creative':
				$resp = $this->_api->SimbaRptAdgroupcreativebaseGetRequest($req);
				return (array) $resp['rpt_adgroupcreative_base_list'];			
			break;
			
			case 'rpt_demographic':
				$resp = $this->_api->SimbaRptDemographicbaseGetRequest($req);
				return (array) $resp['rpt_demographic_base_list'];
			break;
			
			case 'rpt_keyword':
			
			break;
			
		}
	}
	
	/**
	 * 调用API获取用户各种实体效果报表汇总数据  soure = SUMMARY , searchType = SUMMARY
	 * 			rpt_customer
	 * 			rpt_campaign 
	 * 			rpt_adgroup
	 * 			rpt_adgroup_place
	 * 			rpt_adgroup_creative
	 * 			rpt_demographic
	 * @param $entity 更新实体表明 
	 * @param number $campaign_id
	 * @param number $adgroup_id
	 * @param string $start
	 * @param string $end
	 * @param array(k=>v) $params 自定义API参数, 具有最高priority.
	 * @return array , 对应时段的数据统计记录，包含base统计和effect统计（汇总数据)
	 */
	public function getSummaryData($user_id , $entity , $campaign_id=0 , $adgroup_id=0 , 
			$startTime=null , $endTime=null, $params = null)
	{
		//统一拼装传递参数，其实每个api都类似，可以多不能少，所以按最多的来
		$subway_token = $this->getSubway($user_id);
		$req['start_time'] = $startTime;
		$req['end_time'] = $endTime;
		$req['page_no'] = 1;
		$req['page_size'] = 500;
		$req['source'] = 'SUMMARY';
		$req['subway_token'] = $subway_token;
		$req['search_type'] = 'SUMMARY';
		if( $campaign_id ){
			$req['campaign_id'] = $campaign_id;
		}
		
		if( $adgroup_id ){
			$req['adgroup_id'] = $adgroup_id;
		}
		
		
		$api_map = array(
					'rpt_customer' => array( 
							'base' =>  'SimbaRptCustbaseGetRequest' , 
							'effect' => 'SimbaRptCusteffectGetRequest',
							'key' => array('date')
					),
				
					'rpt_campaign' => array( 
							'base' =>  'SimbaRptCampaignbaseGetRequest' , 
							'effect' => 'SimbaRptCampaigneffectGetRequest' ,
							'key' => array('campaignId' , 'date')
					),
					
					'rpt_campaign_adgroup' => array( 
							'base' =>  'SimbaRptCampadgroupbaseGetRequest' , 
							'effect' => 'SimbaRptCampadgroupeffectGetRequest',
							'key' => array('campaignId','adgroupId' ,'date'),
						//	'params' => array( 'search_type' => 'SEARCH,CAT,NOSEARCH')
							
					),
				
					'rpt_adgroup' => array( 
							'base' =>  'SimbaRptAdgroupbaseGetRequest' , 
							'effect' => 'SimbaRptAdgroupeffectGetRequest',
							'key' => array('campaignId' ,'adgroupId','date'),
						//	'params' => array( 'search_type' => 'SEARCH,CAT,NOSEARCH')
							
					),
					
					// 已经删除这个API （API 不存在）
					'rpt_adgroup_place' => array( 
							'base' =>  'SimbaRptAdgroupnonsearchbaseGetRequest' , 
							'effect' => 'SimbaRptAdgroupnonsearcheffectGetRequest',
							'key' => array('campaignId' ,'adgroupId', 'placeId' , 'date')
					),
				
					'rpt_adgroup_creative' => array( 
							'base' =>  'SimbaRptAdgroupcreativebaseGetRequest' , 
							'effect' => 'SimbaRptAdgroupcreativeeffectGetRequest',
							'key' => array('campaignId' ,'adgroupId', 'creativeId' , 'date')
					),
				
					'rpt_demographic' => array( 
							'base' =>  'SimbaRptDemographicbaseGetRequest' , 
							'effect' => 'SimbaRptDemographiceffectGetRequest',
							'key' => array('campaignid' , 'demographicsexId', 'demographicpurchaseId', 'demographicstarId', 'date')
					),
				
					'rpt_keyword' =>  array( 
							'base' =>  'SimbaRptAdgroupkeywordbaseGetRequest' , 
							'effect' => 'SimbaRptAdgroupkeywordeffectGetRequest',
							'key' => array('campaignid' ,'adgroupid', 'keywordid' , 'searchtype' , 'source', 'date'),
							'params' => array('source' => 'SUMMARY', 'search_type' => 'SEARCH,CAT,NOSEARCH')
					),
				
					
				);

		$summary = array();
		
		$api_base = $api_map[$entity]['base'];
		$api_effect = $api_map[$entity]['effect'];
		$key_struct = $api_map[$entity]['key'];
		$req = isset( $api_map[$entity]['params'] ) ? array_merge($req , $api_map[$entity]['params'] ) : $req;
		$req = isset( $params ) ? array_merge($req, $params) : $req; 
		$has_more_base = true;
		$has_more_effect = true;
		$i = 3;
		while( $has_more_base && $has_more_effect && $i > 0){
			if($has_more_base){
				$resp = $this->_api->$api_base($req);
				$basedata = (array) array_pop( $resp );
				if($basedata) {
					foreach($basedata as &$d){
						$d=(array) $d;
						//处理field不一致的问题
						$this->mapTaobaoFieldsToLocal($d);
						$d['taobao_user_id'] = $user_id;
						$unique_key = '';
						foreach($key_struct as $k){
							$unique_key .= $d[$k];
						}
					
						$summary[$unique_key] = $d;
					}
				}
			}
			
			if( $has_more_effect ){
				$resp = $this->_api->$api_effect($req);
				$effectdata = (array) array_pop( $resp );
				if($effectdata) {
					foreach($effectdata as &$d){
						$d =(array) $d;
						
						$unique_key = '';
						foreach($key_struct as $k){
							$unique_key .= $d[$k];
						}
						
						if( isset( $summary[$unique_key] ) ){
							$summary[$unique_key] = $this->mergeSummaryOfBaseEffectData( $summary[$unique_key] , $d);
						}
					}
				}
			}
			 
			$req['page_no'] = $req['page_no'] + 1;
			$has_more_base = (count($basedata) < 500 && count($basedata) > 0) ? false : true;
			$has_more_effect = (count($effectdata) < 500 && count($effectdata) > 0) ? false : true;
			$i--;
			sleep(1);
		}
		//插入前检查数据完整性防止插入出错
		$this->checkFields($summary);
		return array_values ( $summary );		
	}
	
	/**
	 * 供script脚本使用保存报表数据
	 * 
	 * 获取用户各种实体效果报表汇总数据  soure = SUMMARY , searchType = SUMMARY
	 * 			rpt_customer
	 * 			rpt_campaign 
	 * 			rpt_adgroup
	 * 			rpt_adgroup_place
	 * 			rpt_adgroup_creative
	 * 			rpt_demographic
	 * 最大执行3次 如果三次还没有获取到数据那就退出
	 * @param $entity 更新实体表明 
	 * @param number $campaign_id
	 * @param number $adgroup_id
	 * @param string $start
	 * @param string $end
	 * @return mixed , int 表示插入的记录数量，false出错
	 */
	public function syncSummaryData( $user_id , $entity , $campaign_id=0 , $adgroup_id=0 , $startTime=null , $endTime=null, $api_params = null){
		$summary = $this->getSummaryData($user_id , $entity , $campaign_id , $adgroup_id, $startTime , $endTime, $api_params);
		$inserted = $this->saveRptData($entity, $summary);
		return $inserted ;
	}
	
	
	/**
	 * 保存实体数据到数据库，entity 对应实体表明
	 * @param string $entity , rpt_custom , rpt_campaign , rpt_adgroup ....
	 * @param mixed $summary , 数据 2D array 
	 * 				$this->getSummuaryData的返回值
	 * 				array(
	 * 					0 => array( adgroup_id ) 
	 * 				)
	 * @return int 插入的条数
	 */
	public function saveRptData($entity , $summary)
	{
		if($entity=='rpt_campaign_adgroup'){
			$entity='rpt_adgroup';
		} elseif ($entity=='rpt_keyword') {
			$me = session('me');
			$entity='rpt_keyword'.$me['user_id'];
		}
		$tb = M($entity);
		$chunked_summary = array_chunk($summary, 1000);
		$inserted_num = 0;
		foreach($chunked_summary as $data){
		    $inserted_num += $tb->addAll($data , array() , true);		
		}
		return $inserted_num;
	}
	
	/**
	 * 
	 * 检查数据完整性
	 * 
	 * @param summurry data 
	 * @return void
	 */
	protected function checkFields(&$summary)
	{

		$must_keys = array(
				'cpc' => 'cpc',
				'ctr' => 'ctr',
				'impressions' => 'impressions',
				'cpm' => 'cpm',
				'click' => 'click',
				'aclick' => 'aclick',
				'cost' => 'cost',
				'indirect_pay' => 'indirectpay',
				'direct_pay' => 'directpay',
				'indirect_pay_count' => 'indirectpaycount',
				'direct_pay_count' => 'directpaycount',
				'fav_item_count' => 'favitemcount',
				'fav_shop_count' => 'favshopcount',
				'roi' => 'roi',
                'avgpos' => 'avgpos'
		);
		
		foreach($summary as $key=>$b){
			//保证每条数据的完整性，必须的字段必须要有值，否则设为默认值0
			foreach($must_keys as $mk => $v){
				if(!isset($summary[$key][$mk]) || $summary[$key][$mk] == '' || $summary[$key][$mk] == NULL){
					$summary[$key][$mk] = 0;
				}
			}
			
			ksort( $summary[$key] );
		}
			
	}
	
	/** 
	 * map 淘宝变态的字段名到我们的本地字段名
	 * @param base统计属性或者effect统计属性
	 * @return void
	 */
	public function mapTaobaoFieldsToLocal(&$data)
	{
		$map = array(//todo:大写问题
				'campaignId' => 'campaign_id',
				'campaignid' => 'campaign_id',
				'adgroupId' => 'adgroup_id',
				'adgroupid' => 'adgroup_id',
				'placeId' => 'place_id',
				'creativeId' => 'creative_id',
				'demographicsexId' => 'demographicsex_id',
				'demographicpurchaseId' => 'demographicpurchase_id',
				'demographicstarId' => 'demographicstar_id',					
				'keywordid' => 'keyword_id',
				'searchtype' => 'search_type',
				'favItemCount'=>'fav_item_count',
				'favitemcount'=>'fav_item_count',
				'favShopCount'=>'fav_shop_count',
				'favshopcount'=>'fav_shop_count',
				'indirectpaycount'=>'indirect_pay_count',
				'directpaycount'=>'direct_pay_count',
				'indirectpay'=>'indirect_pay',
				'directpay'=>'direct_pay',
		);
		
		foreach($map as $k=>$v){
			if( isset($data[$k]) ){
				$data[$v] = $data[$k];
			}
		}
		
		if(isset($data['source']) && strlen($data['source']) > 1) { // 如果存在且不是数字
			$source_types = RptBaseModel::$_SOURCE_TYPES;
			$data['source'] = $source_types[$data['source']];
		}
		if(isset($data['search_type']) && strlen($data['search_type']) > 1) {
			$search_types = RptBaseModel::$_SEARCH_TYPES;
			$data['search_type'] = $search_types[$data['search_type']];
		}
	}

	/**
	 * 
	 * 合并base 和 effect data 的函数
	 * *param mix , base 统计属性
	 * *param mix , effect 统计属性
	 */
	protected function mergeSummaryOfBaseEffectData($basedata , $effectdata)
	{
		$map = array(
				'indirect_pay' => 'indirectpay',
				'direct_pay' => 'directpay',
				'indirect_pay_count' => 'indirectpaycount',
				'direct_pay_count' => 'directpaycount',
				'fav_item_count' => 'favitemcount',
				'fav_shop_count' => 'favshopcount',
				'roi' => 'roi',
		);
		
		foreach($map as $k=>$v){
			if( isset($effectdata[$v]) ){
				$basedata[$k] = $effectdata[$v];
			}
		}
				
		return $basedata;
	}
	
	public function getSubway($user_id = 0)
	{
		$defaultValidSeconds = 10 * 3600;
		if ($this->subwayToken == NULL) {
			$storedToken = $user_id ? M('subway_tokens')->where(array(
					'user_id'=>$user_id, 'req_ts' => array('exp', "> CURRENT_TIMESTAMP - $defaultValidSeconds" // valid for 1h
			)))->getField('subway_token') : 0;
			if($storedToken) {
				$this->subwayToken = $storedToken;
			} else {
				$user_nick =  M('users')->where(array('user_id'=>$user_id))->getField('nick');
				$req = array (
				    'nick' => $user_nick
				);
				$resp = $this->_api->SimbaLoginAuthsignGetRequest($req);
				$this->subwayToken = $resp['subway_token'];
				M('subway_tokens')->add(array(
						'user_id' => $user_id,
						'subway_token' => $this->subwayToken,
				), array(), true);
			}
		}
		return $this->subwayToken;
	}
	
	/**
	 * 获取推广计划实时报表数据
	 * @return
	 */
	public function getRealTimeCampaignReport()
	{
		$me = session('me');
		$params['nick'] = $me['nick'];
		$params['the_date'] = date('Y-m-d', time());
		$resp = $this->_api->SimbaRtrptCampaignGetRequest($params);
		return $resp['resultss']->rt_rpt_result_entity_d_t_o;
	}

	/**
	 * 获取类目行业数据
	 * @return [type] [description]
	 */
	public function getCatsData($category_id, $form, $to)
	{
		$params = array(
				'category_id_list' => $category_id,
				'start_date' => $form,
				'end_date' => $to
			);

		$resp = $this->_api->SimbaInsightCatsdataGetRequest($params);
		$resp = object_to_array($resp['cat_data_list']);
		return isset($resp['insight_category_data_d_t_o']) ? $resp['insight_category_data_d_t_o'] : array();
	}
}
